<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { MapLocation, Document, InfoFilled, Bell } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

const userStore = useUserStore()
const username = userStore.userInfo.username

// 道路养护信息
const roadInfo = ref([])

// 加载中状态
const loading = ref(true)

// 加载道路养护信息
const loadRoadMaintenanceInfo = async () => {
  loading.value = true
  try {
    // 创建道路损坏要素图层
    const roadDamageLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
      outFields: ['*']
    })

    // 查询道路损坏数据
    const query = roadDamageLayer.createQuery()
    query.where = "1=1"
    query.outFields = ["*"]
    query.returnGeometry = false

    const results = await roadDamageLayer.queryFeatures(query)
    const features = results.features

    // 按道路名称分组
    const roadGroups = {}
    features.forEach(feature => {
      const roadName = feature.attributes.roadName || '未命名道路'
      if (!roadGroups[roadName]) {
        roadGroups[roadName] = {
          damages: [],
          status: '计划中',
          progress: 0
        }
      }

      roadGroups[roadName].damages.push(feature)

      // 更新状态
      if (feature.attributes.status === '已完成') {
        roadGroups[roadName].completedCount = (roadGroups[roadName].completedCount || 0) + 1
      } else if (feature.attributes.status === '处理中') {
        roadGroups[roadName].status = '养护中'
      }
    })

    // 转换为表格数据格式
    const roadData = Object.keys(roadGroups).map((roadName, index) => {
      const group = roadGroups[roadName]
      const totalDamages = group.damages.length
      const completedDamages = group.completedCount || 0
      const progress = totalDamages > 0 ? Math.round((completedDamages / totalDamages) * 100) : 0

      // 计算状态
      let status = '计划中'
      if (progress === 100) {
        status = '已完成'
      } else if (progress > 0) {
        status = '养护中'
      }

      // 获取日期信息
      const dates = group.damages.map(d => d.attributes.reportTime ? new Date(d.attributes.reportTime) : null).filter(Boolean)
      const startDate = dates.length > 0 ? new Date(Math.min(...dates.map(d => d.getTime()))) : new Date()
      const endDate = new Date(startDate)
      endDate.setDate(endDate.getDate() + 30) // 默认养护期为30天

      // 收集所有维护方法
      const methods = group.damages
        .filter(d => d.attributes.maintainMethod)
        .map(d => d.attributes.maintainMethod)

      return {
        id: index + 1,
        name: roadName,
        status: status,
        progress: progress,
        startDate: startDate.toLocaleDateString(),
        endDate: endDate.toLocaleDateString(),
        description: methods.length > 0 ? methods.join('、') : '道路养护'
      }
    })

    roadInfo.value = roadData
    loading.value = false
  } catch (error) {
    console.error('加载道路养护信息失败', error)
    ElMessage.error('加载道路养护信息失败')
    loading.value = false
  }
}

// 通知公告
const notifications = ref([])

// 加载通知公告
const loadNotifications = async () => {
  try {
    // 创建道路损坏要素图层
    const roadDamageLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
      outFields: ['*']
    })

    // 查询道路损坏数据
    const query = roadDamageLayer.createQuery()
    query.where = "1=1"
    query.outFields = ["*"]
    query.returnGeometry = false
    query.orderByFields = ["reportTime DESC"] // 按报告时间降序排序

    const results = await roadDamageLayer.queryFeatures(query)
    const features = results.features.slice(0, 5) // 只取前5条

    // 转换为通知公告格式
    notifications.value = features.map((feature, index) => {
      const reportTime = feature.attributes.reportTime ? new Date(feature.attributes.reportTime).toLocaleDateString() : '未知日期'
      const roadName = feature.attributes.roadName || '未命名道路'
      const damageType = feature.attributes.damageType || '道路损坏'
      const status = feature.attributes.status || '待处理'

      let title = ''
      let content = ''

      if (status === '已完成') {
        title = `${roadName}养护工作已完成`
        content = `${roadName}的${damageType}问题已于${feature.attributes.maintainTime || reportTime}完成维修，维修方式为${feature.attributes.maintainMethod || '常规养护'}。`
      } else if (status === '处理中') {
        title = `${roadName}养护工作进行中`
        content = `${roadName}的${damageType}问题正在进行维修，请过往车辆注意安全。`
      } else {
        title = `${roadName}道路损坏报告`
        content = `${roadName}发现${damageType}问题，已于${reportTime}上报，等待处理。`
      }

      return {
        id: index + 1,
        title: title,
        date: reportTime,
        content: content
      }
    })
  } catch (error) {
    console.error('加载通知公告失败', error)
    ElMessage.error('加载通知公告失败')

    // 加载失败时使用默认数据
    notifications.value = [
      {
        id: 1,
        title: '系统公告',
        date: new Date().toLocaleDateString(),
        content: '欢迎使用道路养护管理系统，您可以在这里查看道路养护信息和上报道路损坏。'
      }
    ]
  }
}

// 地图相关变量
let view: __esri.MapView
let roadDamageLayer: __esri.FeatureLayer

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  // 创建地图视图
  view = new MapView({
    container: 'userAreaMapView',
    map: map,
    center: [116.3912, 39.9073], // 北京市中心坐标
    zoom: 12,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建道路损坏要素图层
  roadDamageLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
    outFields: ['*'],
    popupTemplate: {
      title: '{roadName}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'damageType', label: '损坏类型' },
            { fieldName: 'severityLevel', label: '严重程度' },
            { fieldName: 'reportTime', label: '报告时间' },
            { fieldName: 'status', label: '处理状态' },
            { fieldName: 'description', label: '描述' },
          ],
        },
      ],
    },
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-line',
        color: [255, 0, 0, 0.8], // 红色
        width: 4,
        style: 'solid',
      },
    },
  })

  // 将图层添加到地图
  map.add(roadDamageLayer)
}

// 页面加载时获取数据
onMounted(() => {
  loadRoadMaintenanceInfo()
  loadNotifications()
  initMap()
})

// 获取状态对应的标签类型
const getStatusType = (status) => {
  switch (status) {
    case '养护中':
      return 'warning'
    case '已完成':
      return 'success'
    case '计划中':
      return 'info'
    default:
      return ''
  }
}
</script>

<template>
  <div class="user-container">
    <el-row :gutter="20" class="welcome-row">
      <el-col :span="24">
        <el-card class="welcome-card">
          <div class="welcome-content">
            <h2>欢迎，{{ username }}</h2>
            <p>感谢您使用道路养护管理系统。在这里，您可以查看道路养护信息、通知公告和地图数据。</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="main-row">
      <el-col :span="16">
        <el-card class="road-info-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>道路养护信息</span>
            </div>
          </template>

          <el-table v-loading="loading" :data="roadInfo" style="width: 100%">
            <el-table-column prop="name" label="道路名称" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="progress" label="进度" width="180">
              <template #default="scope">
                <el-progress :percentage="scope.row.progress" :status="scope.row.progress === 100 ? 'success' : ''" />
              </template>
            </el-table-column>
            <el-table-column prop="startDate" label="开始日期" width="120" />
            <el-table-column prop="endDate" label="结束日期" width="120" />
            <el-table-column label="操作" width="100">
              <template #default>
                <el-button size="small" type="primary" plain>详情</el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty v-if="!loading" description="暂无道路养护信息" />
            </template>
          </el-table>
        </el-card>

        <el-card class="notification-card">
          <template #header>
            <div class="card-header">
              <el-icon><Bell /></el-icon>
              <span>通知公告</span>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
              v-for="item in notifications"
              :key="item.id"
              :timestamp="item.date"
              placement="top"
            >
              <el-card class="notification-item">
                <h4>{{ item.title }}</h4>
                <p>{{ item.content }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <el-icon><MapLocation /></el-icon>
              <span>养护区域地图</span>
            </div>
          </template>

          <div id="userAreaMapView" class="map-container"></div>
        </el-card>

        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>系统信息</span>
            </div>
          </template>

          <div class="info-content">
            <p><strong>系统版本：</strong> v1.0.0</p>
            <p><strong>最近更新：</strong> 2023-06-01</p>
            <p><strong>技术支持：</strong> support@example.com</p>
            <p><strong>帮助文档：</strong> <el-link type="primary">查看文档</el-link></p>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.user-container {
  padding: 10px;
}

.welcome-row {
  margin-bottom: 20px;
}

.welcome-card {
  background-color: #ecf5ff;
}

.welcome-content {
  padding: 10px;
}

.welcome-content h2 {
  color: #409EFF;
  margin-bottom: 10px;
}

.main-row {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
}

.card-header .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.road-info-card,
.notification-card {
  margin-bottom: 20px;
}

.notification-item {
  margin-bottom: 10px;
}

.notification-item h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.notification-item p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.map-container {
  height: 300px;
  width: 100%;
  border-radius: 4px;
}

.info-card {
  margin-top: 20px;
}

.info-content {
  padding: 10px;
}

.info-content p {
  margin: 10px 0;
  color: #606266;
}
</style>
